<?php
/**
 * @desc 支付宝.异步通知
 * @document https://docs.open.alipay.com/204/105301
 * @author Vincent
 */

namespace young\payment;

class AliNotify extends AliConfig
{

    public function run($callback)
    {
        return $this->handle($callback);
    }

    /**
     * @param $callback
     * @return string
     * @throws \Exception
     * callback为商家业务逻辑处理回调函数，处理成功后返回true（已验证签名）
     */
    private function handle($callback)
    {
        $post = $_POST;
        if (empty($post) || !is_array($post)) {
            return '无效数据';
        }
        $rsa2 = new AliRsa2;

        $signData = $post;
        unset($signData['sign'], $signData['sign_type']);
        ksort($signData);
        $signData = urldecode(http_build_query($signData));

        //验证签名
        $rsa2->setKey($rsa2->getRsaKeyValue($this->aliPublicKey, 'public'));
        $verifySign = $rsa2->rsaVerify($signData, $post['sign']);

        if ($verifySign === true && $post['seller_id'] == $this->sellerId && $post['app_id'] == $this->appId && $post['trade_status'] == 'TRADE_SUCCESS') {
            $data = [
                'order_sn' => $post['out_trade_no'],
                'trade_no' => $post['trade_no'],
                'total_amount' => $post['total_amount']//交易总金额
            ];
            if ($callback($data) === true) {
                return 'success';
            } else {
                return 'failed';
            }
        } else {
            return '签名失败';
        }
    }
}